package edu.ustb.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import java.io.File;
import java.io.FileReader;
import java.util.*;

/**
 * @Author ldd
 * @Create 2021-06-03 17:14
 */
public class JsonParseUtil {

    /**
     * 获取相对路径
     * @param entry
     * @return charNewArray 为最后一个路径的值
     */
    public static String getPath(Map.Entry<String, String> entry){
        //最后一个 "/" 索引位置
        int index = entry.getKey().lastIndexOf("/");

//        char[] charArray = entry.getKey().toCharArray();
//        char[] charNewArray = new char[charArray.length - index];
//        for (int i = 0; i < charArray.length - index; i++) {
//            charNewArray[i] = charArray[i + index];
//        }
//        return charNewArray;
        return entry.getKey().substring(index);
    }

    /**
     * JSON字符串间转换
     * @param jsonStr
     */
    public static void json2json(String jsonStr, boolean isTransaction, HashMap<String, String> map){

        //获取json对象
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);

        //输出头部
        JSONArray tags = (JSONArray) jsonObj.getJSONArray("tags");
//        System.out.println(tags);
//        [{
//		    "name": "***********",
//		    "description": "************"
//	      }]
        for (int i = 0; i < tags.size(); i++) {
            JSONObject tagsObj = (JSONObject) tags.get(i);
            String description = (String)tagsObj.get("description");
            int index = description.lastIndexOf("Controller");
            System.out.println("asset " + description.substring(0,index) + ": type Service {");
        }

//        for (Map.Entry<String, String> entry : jsonMapHead.entrySet()) {
//            if ("description".equals(entry.getKey())) {
//                String description = entry.getValue();
//                int index = description.lastIndexOf("Controller");
//                System.out.println("asset " + description.substring(0,index) + " : type Service {");
//            }
//        }

        //第一部分 instances
        Object info = jsonObj.get("info");
        System.out.println("\t" + "instances[" + "\n\t\t" + info + "],");
        //第二部分 paths
        Object pathObj = jsonObj.get("paths");
        JSONObject pathObj1 = (JSONObject) pathObj;

        System.out.print("\t" + "paths[" + "\n\t\t" + "{path: " + "\"");

        //返回有序 --> LinkedHashMap
        LinkedHashMap<String, String> jsonMapBody = JSON.parseObject(String.valueOf(pathObj1), new TypeReference<LinkedHashMap<String, String>>() {
        });

        for (Map.Entry<String, String> entry : jsonMapBody.entrySet()) {

            if (entry.getKey().contains("/")) {
                String path = getPath(entry);
                System.out.print(path);
                Object pathObj2 = pathObj1.get(entry.getKey());
                JSONObject pathObj3 = (JSONObject) pathObj2;

                Object pathObj4 = pathObj3.get("get");
                JSONObject paths = (JSONObject) pathObj4;
                System.out.print( "\","+ "label: \"" + paths.get("summary") + "\" ,");
                System.out.print( "parameters: \"" + paths.get("parameters") + "\" ,");
                String method = (String) paths.get("operationId");
                if (method.contains("GET")) {
                    System.out.print( "method: \"" + "GET" + "\"");
                } else if (method.contains("POST")){
                    System.out.print( "method: \"" + "POST" + "\"");
                }
                System.out.println("],");
                //第三部分 responses
                System.out.println("\t" + "responses[" + "\n\t\t" + ((JSONObject) pathObj4).get("responses") + "],");
            }

        }

        //第四部分 rights
        System.out.println("\t" + "rights[");
        Set<Map.Entry<String, String>> set = map.entrySet();
        Iterator<Map.Entry<String, String>> iterator = set.iterator();
        while (iterator.hasNext()) {
            Map.Entry mapEntry=(Map.Entry)iterator.next();
            System.out.print( "\t\t{" + mapEntry.getKey() + " : " + mapEntry.getValue() + "}");
            if (iterator.hasNext()) {
                System.out.println(",");
            } else {
                System.out.println("]");
            }
        }

        //第五部分 price
        if (true == isTransaction) {
            String price = "Money";
            System.out.println("\t" + "price: " + price );
        }

        //输出尾部
        System.out.println("}");
    }

    public static String readJsonStrFromFile(File file) {
        StringBuilder stringBuilder = new StringBuilder();
        char[] buff = new char[512];
        try {
            FileReader fileReader = new FileReader(file);
            int len = fileReader.read(buff);
            while (len > 0) {
                stringBuilder.append(buff, 0, len);
                len = fileReader.read(buff);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}
